package com.wanyangproject.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wanyangproject.activity.LoginActivity;
import com.wanyangproject.entity.WeinXinTokenEntity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import cn.sharesdk.wechat.utils.WXAppExtendObject;
import cn.sharesdk.wechat.utils.WXMediaMessage;
import okhttp3.Call;

/**
 * Created by 甜甜 on 2018/8/26.
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        LoginActivity.iwxapi = WXAPIFactory.createWXAPI(this, "wx363ae6178db5e958", false);
//        LoginActivity.iwxapi.registerApp("wx363ae6178db5e958");
        try {
            LoginActivity.iwxapi.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("///////111112222222");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        LoginActivity.iwxapi.handleIntent(intent, this);
    }


    @Override
    public void onReq(BaseReq baseReq) {
        System.out.println(baseReq + "           11111111111");
    }


    @Override
    public void onResp(BaseResp baseResp) {
        //        Throwable aa = new  Throwable("2");
//        CrashReport.postCatchedException(aa);
        System.out.println("22222222222");
        int type = baseResp.getType();
        System.out.println(baseResp.errCode + "        baseResp.errCode");

        System.out.println(type + "        baseResp.errCode1");
        System.out.println(baseResp.errStr + "        baseResp.errCode");



//        Toast.makeText(this, baseResp.errCode+"", Toast.LENGTH_SHORT).show();
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
                    if (baseResp instanceof SendAuth.Resp) {
                        SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
                        //获取微信传回的code
                        String code = newResp.code;
                        System.out.println(code + "   code");

                        OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx363ae6178db5e958&secret=bf4ea0f9086f9d8d96d5eaac9311288c&code=" + code + "&grant_type=authorization_code")
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {

                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
//                                    Throwable aa = new  Throwable("3");
//                                    CrashReport.postCatchedException(aa);
                                        System.out.println("3333333333");

                                        System.out.println(response + "     获取access_token");
                                        Gson gson = new Gson();
                                        WeinXinTokenEntity weinXinTokenEntity = gson.fromJson(response, WeinXinTokenEntity.class);

                                        if (response.indexOf("200") != -1) {
                                            Intent intent = new Intent();
                                            intent.putExtra("wxopenid", weinXinTokenEntity.getOpenid());
                                            intent.setAction("wx");
                                            sendBroadcast(intent);
                                        }


//                                    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/userinfo?access_token=" + weinXinTokenEntity.getAccess_token() + "&openid=" + weinXinTokenEntity.getOpenid())
//                                            .build()
//                                            .execute(new StringCallback() {
//                                                @Override
//                                                public void onError(Call call, Exception e, int id) {
//                                                    Toast.makeText(WXEntryActivity.this, "请检查您的网络连接", Toast.LENGTH_SHORT).show();
//                                                }
//
//                                                @Override
//                                                public void onResponse(String response, int id) {
////                                                    Throwable aa = new  Throwable("4");
////                                                    CrashReport.postCatchedException(aa);
//                                                    System.out.println("4444444444");
//
//                                                    System.out.println(response + "    获取用户信息");
//                                                    Gson gson1 = new Gson();
//                                                    weiXinYongHuXinXiEntity = gson1.fromJson(response, WeiXinYongHuXinXiEntity.class);
//
//                                                    Intent intent=new Intent();
//                                                    intent.putExtra("wxopenid",weiXinYongHuXinXiEntity.getOpenid());
//                                                    intent.putExtra("wxnickname",weiXinYongHuXinXiEntity.getNickname());
//                                                    intent.putExtra("wxheadimgurl",weiXinYongHuXinXiEntity.getHeadimgurl());
//                                                    intent.setAction("abcdef");
//                                                    sendBroadcast(intent);
//
//                                                }
//                                            });
                                    }
                                });
                    }
                }
//                else if (baseResp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                    //分享
//                        Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();

//                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                //发送取消
//                Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //发送被拒绝
//                Toast.makeText(this, "拒绝", Toast.LENGTH_SHORT).show();
                break;
            default:
                //发送返回
//                Toast.makeText(this, "返回", Toast.LENGTH_SHORT).show();
                break;
        }
        finish();
    }


//
//
//
//    /**
//     * 处理微信发出的向第三方应用请求app message
//     * <p>
//     * 在微信客户端中的聊天页面有“添加工具”，可以将本应用的图标添加到其中
//     * 此后点击图标，下面的代码会被执行。Demo仅仅只是打开自己而已，但你可
//     * 做点其他的事情，包括根本不打开任何页面
//     */
//    public void onGetMessageFromWXReq(WXMediaMessage msg) {
//        if (msg != null) {
//            Intent iLaunchMyself = getPackageManager().getLaunchIntentForPackage(getPackageName());
//            startActivity(iLaunchMyself);
//        }
//    }
//
//    /**
//     * 处理微信向第三方应用发起的消息
//     * <p>
//     * 此处用来接收从微信发送过来的消息，比方说本demo在wechatpage里面分享
//     * 应用时可以不分享应用文件，而分享一段应用的自定义信息。接受方的微信
//     * 客户端会通过这个方法，将这个信息发送回接收方手机上的本demo中，当作
//     * 回调。
//     * <p>
//     * 本Demo只是将信息展示出来，但你可做点其他的事情，而不仅仅只是Toast
//     */
//    public void onShowMessageFromWXReq(WXMediaMessage msg) {
//        if (msg != null && msg.mediaObject != null
//                && (msg.mediaObject instanceof WXAppExtendObject)) {
//            WXAppExtendObject obj = (WXAppExtendObject) msg.mediaObject;
//            Toast.makeText(this, obj.extInfo, Toast.LENGTH_SHORT).show();
//        }
//    }
//



}
